# Copyright 2006 Michael Gorsuch <michael@styledbits.com>

# This file is part of GrabTheMic <http://www.grabthemic.org>.

# GrabTheMic is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


class Story < ActiveRecord::Base
  
  has_many :votes
  belongs_to :user
  has_many :comments
  
  validates_presence_of :url
  validates_presence_of :title
  validates_presence_of :user
  
  validates_uniqueness_of :url, :message => "has already been submitted"
  
  def before_save
    calculate_points
  end
  
  def vote_down(user)
    remove_vote(user)
    vote = Vote.new
    vote.story = self
    vote.user = user
    vote.value = -1
    vote.save
    self.save
  end
  
  def vote_up(user)
    remove_vote(user)
    vote = Vote.new
    vote.story = self
    vote.user = user
    vote.value = 1
    vote.save
    self.save
  end
  
  def remove_vote(user)
    vote = self.votes.find_by_user_id(user.id)
    if vote
      vote.destroy
      self.save
    end
  end
          
  def calculate_points
    self.points = 0
    self.votes.reload  
    self.votes.each do |v|
      self.points += v.value
    end
  end
    
end
